package com.example.fw;

import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.GroupObject;

public class GroupHelper extends HelperWithWebDriverBase {

	private Groups groupCash;

	public GroupHelper (ApplicationManager manager) {
		super(manager);
	}

	public Groups getGroups() {
		if (groupCash == null) {
			buildGroupCash();
		}
		return groupCash;
	}
	
	private void buildGroupCash() {
		HashSet<GroupObject> set = new HashSet<GroupObject>();
		manager.getNavigationHelper().goToGroupListPage();
		WebElement form = findElements(By.tagName("form")).get(1);
		List<WebElement> checkboxes = form.findElements(By.name("selected[]"));
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			Pattern p = Pattern.compile(".*\\((.*)\\)");
			Matcher m = p.matcher(title);
			if (m.matches()) {
				title = m.group(1);
			}
			GroupObject group = new GroupObject()
				.setName(title)
				.setId(checkbox.getAttribute("value"));
			set.add(group);
		}
		groupCash = new Groups(set);
	}
	
	public void createGroup(GroupObject groupObject) {
		initGroupCreation();
		fillGroupForm(groupObject);
		submitGroupCreation();
		manager.getNavigationHelper().returnToGroupListPage();
		groupCash = null;
		}

	public void modifyGroup(GroupObject group, GroupObject groupObject) {
		markGroup(group);
		initGroupModification();
		fillGroupForm(groupObject);
		submitGroupModification();
		manager.getNavigationHelper().returnToGroupListPage();
		groupCash = null;
	}

	public void deleteGroup(GroupObject group) {
		markGroup(group);
		submitGroupDelete();
		manager.getNavigationHelper().returnToGroupListPage();
		groupCash = null;
	}
	
	private void initGroupCreation() {
		click(By.name("new"));
	}
	
	private void initGroupModification() {	
		click(By.name("edit"));
	}

	private void fillGroupForm(GroupObject groupObject) {
		type(By.name("group_name"), groupObject.name);
		type(By.name("group_header"), groupObject.header);
		type(By.name("group_footer"), groupObject.footer);
	}
	
	private void submitGroupCreation() {
		click(By.name("submit"));
	}

	private void submitGroupModification() {
		click(By.name("update"));
	}
	
	private void markGroup(GroupObject group) {
	    findElement(By.xpath("//input[@value='" + group.id + "']")).click();
	}

	private void submitGroupDelete() {
		click(By.name("delete"));
	}
	  
}
